import jwt from 'jsonwebtoken'
import { readBody, createError, defineEventHandler, getCookie } from 'h3'
import type { ApiResponse } from '~/types/common'

export default defineEventHandler(async (event) => {
  try {
    // 从cookie获取刷新token
    const refreshToken = getCookie(event, 'refreshToken')

    if (!refreshToken) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌不存在',
        message: '刷新令牌不存在，请重新登录'
      })
    }

    // 验证刷新token
    let decoded: any
    try {
      decoded = jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN_SECRET || 'your-refresh-secret-key'
      )
    } catch (error) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Invalid refresh token',
        message: '刷新令牌无效，请重新登录'
      })
    }

    // 检查token类型
    if (decoded.type !== 'refresh') {
      throw createError({
        statusCode: 401,
        statusMessage: 'Invalid token type',
        message: '无效的令牌类型'
      })
    }

    // 生成新的访问token
    const accessToken = jwt.sign(
      { userId: decoded.userId },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '5m' }
    )

    // 生成新的刷新token（可选：每次刷新都生成新的刷新token）
    const newRefreshToken = jwt.sign(
      { userId: decoded.userId, type: 'refresh' },
      process.env.REFRESH_TOKEN_SECRET || 'your-refresh-secret-key',
      { expiresIn: '7d' }
    )

    // 设置新的token到cookie
    setCookie(event, 'accessToken', accessToken, {
      maxAge: 5 * 60, // 5分钟
      sameSite: 'strict',
      secure: process.env.NODE_ENV === 'production'
    })

    setCookie(event, 'refreshToken', newRefreshToken, {
      maxAge: 7 * 24 * 60 * 60, // 7天
      sameSite: 'strict',
      secure: process.env.NODE_ENV === 'production',
      httpOnly: true
    })

    // 返回新的token
    return {
      code: 200,
      statusMessage: '成功',
      message: 'Token刷新成功',
      data: {
        accessToken,
        refreshToken: newRefreshToken
      }
    } as ApiResponse<{
      accessToken: string
      refreshToken: string
    }>
  } catch (error: any) {
    if (error?.statusCode) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: '服务器错误',
      message: '刷新令牌时发生错误，请稍后再试'
    })
  }
})
